#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <libgen.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <getopt.h>
#include "ds18b20_temp.h"
#include "database.h"
#include "socket.h"
#include "packet.h"

int pro_stop = 0;

void print_usage(char *progname)
{
	printf("%s usage: \n", progname);
	printf("-h(--hostname): specify server IP address\n");
	printf("-p(--port): specify server port\n");
	printf("-t(--interval): specify date collection interval time.\n");
	printf("-H(--Help): print this help information.\n");
	return ;
}

int main(int argc, char **argv)
{
	char			data[512];
	int			   	rv = -1;
	char       		*hostname = NULL;
	int    		 	port = 0;
	int				interval=5;
	int            	last_time = 0;
	time_t         	now_time;
	int				ch;
	char 		   	*progname = NULL;
	char			*filename="data.db";
	int 			sample_flag;//采样标志
	packet_t		pack;
	socket_t		sock;

	struct option   opts[] = 
	{
		{"hostname", required_argument, NULL, 'h'},
		{"port", required_argument, NULL, 'p'},
		{"interval", required_argument, NULL, 't'},
		{"help", no_argument, NULL, 'H'},
		{NULL,0,NULL,0}
	};

	progname = basename(argv[0]);

	while ((ch = getopt_long(argc, argv, "h:p:t:H", opts, NULL)) != -1)
	{
		switch(ch)
		{
			case 'h':
				hostname = optarg;
				break;
			case 'p':
				port = atoi(optarg);
				break;
			case 't':
				interval = atoi(optarg);
				break;
			case 'H':
				print_usage(argv[0]);
				return 0;
		}
	}

	if( !hostname || !port )
	{
		print_usage(progname);
		return -1;
	}

	socket_init(&sock, hostname, port);

	if ( db_create(filename) < 0 )
	{
		return -2;
	}

	while(!pro_stop)
	{
		sample_flag = 0;

		// 判断是否要采样 
		time(&now_time);
		if( (now_time - last_time) > interval-1 )
		{
			rv = sample_temperature(&pack);
			if( rv < 0 ) //出错时通过rv的值查看查函数get_temp()的错误地方
			{
				printf("Get data failure, return value: %d \n",rv);
				return -1;
			}

			sample_flag = 1;
			last_time = now_time;
		}

		// 判断socket连没连上 
		if( sock.fd < 0 )
        {
            socket_connect(&sock);
        }
		
		if( !check_connect(sock.fd) )//没连上
		{
			if( sock.fd > 0 )
            {
                printf("socket got disconnected, terminate it and reconnect now.\n");
                socket_close(&sock); /* close the soket */
            }
		}

		// 采样了，放进数据库 
		if( sock.fd < 0 )
		{
			if(sample_flag)
			{
				db_insert(&pack);
			}
			continue;//Therefore, the following code is connected = 1
		}

		// 连上了  
		// 1、采样了就直接发送数据 
		if( sample_flag )
		{
			memset(data, 0, sizeof(data));
			pack_data( &pack, data, sizeof(data));
			printf("data=%s\n", data);
			if( write(sock.fd, data, strlen(data)) < 0)
			{
				printf("write sample to server failure:%s\n", strerror(errno));
				db_insert(&pack);//发送失败要将数据放进数据库
				socket_close(&sock);
			}
		}

		// 2、如果数据库中有数据，就发送数据 
		if( db_firstdata(&pack) == 1 )
		{
			memset(data, 0, sizeof(data));
			//查找数据库第一行的数据，放进db_buf
			pack_data( &pack, data, sizeof(data));
			printf("db_buf=%s\n", data);

			if( write(sock.fd, data, strlen(data)) < 0)
			{
				printf("write db_sample to server failure:%s\n", strerror(errno));
				db_insert(&pack);//发送失败要将数据放进数据库
				socket_close(&sock);
			}
			else
			{
				printf("Send db_buf_first to server successfully !\n");
				db_delete();//删除第一条数据
			}
		}	
	} /* while(!pro_stop) */

	db_close();
	return 0;
} 
